package com.csmd.gateway.filter;

import com.csmd.gateway.props.AuthProperties;
import com.csmd.gateway.provider.AuthProvider;
import com.csmd.gateway.provider.ResponseProvider;
import com.csmd.gateway.utils.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 *
 * 鉴权认证
 * @ClassName AuthFilter
 * @Description 498982703@qq.com
 * @Author gary
 * @Date 2020/11/11 17:30
 * @Version 1.0
 */

@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private AuthProperties authProperties;

    private ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (isSkip(path)) {
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
        String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
        if (StringUtils.isAllBlank(headerToken, paramToken)) {
            return unAuth(response, "缺失令牌,鉴权失败");
        }
        String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
        String token = JwtUtil.getToken(auth);
        Claims claims = JwtUtil.parseJWT(token);
        if (chain == null) {
            return unAuth(response, "请求未授权");
        }
        return chain.filter(exchange);
    }

    private boolean isSkip(String path) {
        return AuthProvider.getDefaultSkipUrl()
                .stream()
                .map(url->url.replace(AuthProvider.TARGET,AuthProvider.REPLACEMENT))
                .anyMatch(path::contains)||
                authProperties.getSkipUrl()
                        .stream()
                        .map(url->url.replace(AuthProvider.TARGET,AuthProvider.REPLACEMENT))
                        .anyMatch(path::contains);

    }

    private Mono<Void> unAuth(ServerHttpResponse response, String msg) {
        response.setStatusCode((HttpStatus.UNAUTHORIZED));
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = "";
        try {
             result = objectMapper.writeValueAsString(ResponseProvider.unAuth(msg));
        } catch (JsonProcessingException e) {
            log.error("unAuth error:{}", msg, e);
        }
        DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(buffer));

    }

    @Override
    public int getOrder() {
        return -100;
    }
}
